// 全局loading状态管理
let loadingCount = 0
let loadingTimer = null

// 显示loading
const showLoading = (mask = true, title = '加载中...') => {
  if (loadingCount === 0) {
    // 防抖处理，避免快速连续请求时loading闪烁
    clearTimeout(loadingTimer)
    loadingTimer = setTimeout(() => {
      uni.showLoading({
        title,
        mask // 是否显示透明蒙层，防止触摸穿透
      })
    }, 100)
  }
  loadingCount++
}

// 隐藏loading
const hideLoading = () => {
  loadingCount--
  if (loadingCount <= 0) {
    loadingCount = 0
    clearTimeout(loadingTimer)
    uni.hideLoading()
  }
}

// 请求拦截器
const requestInterceptor = config => {
  // 添加token
  const token = uni.getStorageSync('token')
  if (token) {
    config.header = {
      ...config.header,
      Authorization: `Bearer ${token}`
    }
  }

  // 添加公共请求头
  config.header = {
    'Content-Type': 'application/json',
    ...config.header
  }

  return config
}

// 响应拦截器
const responseInterceptor = response => {
  const { data, statusCode } = response
  console.log(response)
  // 处理HTTP状态码
  if (statusCode === 200) {
    // 处理业务状态码
    if (data.code === 0 || data.code === 200) {
      return data.data || data
    } else {
      // 业务错误
      uni.showToast({
        title: data.message || '请求失败',
        icon: 'none'
      })
      return Promise.reject(new Error(data.message || '请求失败'))
    }
  } else if (statusCode === 401) {
    // token过期，清除登录信息
    uni.removeStorageSync('token')
    uni.showToast({
      title: '登录已过期，请重新登录',
      icon: 'none'
    })
    // 跳转到登录页
    uni.reLaunch({
      url: '/pages/login/login'
    })
    return Promise.reject(new Error('登录已过期'))
  } else {
    // 其他HTTP错误
    uni.showToast({
      title: `请求失败 ${statusCode}`,
      icon: 'none'
    })
    return Promise.reject(new Error(`HTTP Error: ${statusCode}`))
  }
}

// 错误处理
const errorHandler = error => {
  console.error('Request Error:', error)

  if (error.errMsg) {
    // uni.request的错误
    if (error.errMsg.includes('timeout')) {
      uni.showToast({
        title: '请求超时，请检查网络',
        icon: 'none'
      })
    } else if (error.errMsg.includes('fail')) {
      uni.showToast({
        title: '网络连接失败',
        icon: 'none'
      })
    }
  }

  return Promise.reject(error)
}

// 封装的请求函数
const request = options => {
  return new Promise((resolve, reject) => {
    // 处理URL
    let url = options.url
    if (!url.startsWith('http')) {
      url = import.meta.env.VITE_PROXY_TARGET + url
    }

    // 请求配置 - 合并默认配置和用户配置
    const defaultConfig = {
      loading: true, // 默认显示loading
      loadingMask: false, // 默认显示蒙层，防止用户操作
      loadingTitle: '加载中...', // 默认loading文字
      timeout: 20000
    }

    const config = {
      url,
      method: options.method || 'GET',
      data: options.data || {},
      header: options.header || {},
      ...defaultConfig,
      ...options
    }

    // 应用请求拦截器
    const interceptedConfig = requestInterceptor(config)

    // 显示loading
    if (config.loading) {
      showLoading(config.loadingMask, config.loadingTitle)
    }

    // 发起请求
    uni.request({
      ...interceptedConfig,
      success: response => {
        // 隐藏loading
        if (config.loading) {
          hideLoading()
        }
        try {
          const result = responseInterceptor(response)
          resolve(result)
        } catch (error) {
          reject(error)
        }
      },
      fail: error => {
        // 隐藏loading
        if (config.loading) {
          hideLoading()
        }
        errorHandler(error).catch(reject)
      }
    })
  })
}

// 便捷方法
export const get = (url, params = {}, options = {}) => {
  return request({
    url,
    method: 'GET',
    data: params,
    ...options
  })
}

export const post = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  })
}

export const put = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    ...options
  })
}

export const del = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'DELETE',
    data,
    ...options
  })
}

// 文件上传
export const upload = (
  url,
  filePath,
  name = 'file',
  formData = {},
  options = {}
) => {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    const header = {}

    if (token) {
      header.Authorization = `Bearer ${token}`
    }

    // 处理URL
    if (!url.startsWith('http')) {
      url = import.meta.env.VITE_PROXY_TARGET + url
    }

    // 合并默认配置
    const defaultConfig = {
      loading: true,
      loadingMask: true,
      loadingTitle: '上传中...'
    }
    const config = { ...defaultConfig, ...options }

    // 显示loading
    if (config.loading) {
      showLoading(config.loadingMask, config.loadingTitle)
    }

    uni.uploadFile({
      url,
      filePath,
      name,
      formData,
      header,
      success: response => {
        // 隐藏loading
        if (config.loading) {
          hideLoading()
        }
        try {
          const data = JSON.parse(response.data)
          if (data.code === 0 || data.code === 200) {
            resolve(data.data || data)
          } else {
            uni.showToast({
              title: data.message || '上传失败',
              icon: 'none'
            })
            reject(new Error(data.message || '上传失败'))
          }
        } catch (error) {
          reject(error)
        }
      },
      fail: error => {
        // 隐藏loading
        if (config.loading) {
          hideLoading()
        }
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        })
        reject(error)
      }
    })
  })
}

export default request
